package com.rtx.wms.std.bak.service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.wms.std.bak.bean.MysqlTableField;
import com.rtx.wms.std.bak.mapper.BakDataMapper;

@Service
public class BakLogService {
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	BakDataMapper bakDataMapper;
	
	@DataSourceAnnotation
	public void handleTableBak(String datasourcekey,String tablename,String dateCoulmns,String otherCondition,int day) {
		String bakSql = createBakSql(tablename,dateCoulmns,otherCondition,day);
		String delSql =deleteSql(tablename,dateCoulmns,otherCondition,day);
		log.info(bakSql);
		log.info(delSql);
		
		bakDataMapper.insBak(bakSql);
		
		bakDataMapper.delSql(delSql);
	}

	public List<MysqlTableField> queryFieldByTableName(String tablename) {
		String sql ="show full columns from "+tablename;
		return bakDataMapper.queryField(sql);
	};
	
	public String createBakSql(String tablename,String dateCoulmns,String otherCondition,int day) {
		List<MysqlTableField> list = queryFieldByTableName(tablename);
		String columns = list.stream().map(Field->Field.getField()).collect(Collectors.joining(","));
		
		StringBuffer bakSql = new StringBuffer();
		bakSql.append("insert into "+tablename+"_bak(");
		bakSql.append(columns);
		bakSql.append(")");
		bakSql.append("select ");
		bakSql.append(columns);
		bakSql.append(" from ");
		bakSql.append(tablename);
		bakSql.append(" where ");
		bakSql.append("date_format("+dateCoulmns+",'%Y%m%d') <");
		bakSql.append("'"+LocalDateTime.now().plusDays(day).format(DateTimeFormatter.ofPattern("yyyyMMdd"))+"'");
		if(StringUtils.hasLength(otherCondition)) {
			bakSql.append("and "+otherCondition);
		}
		return bakSql.toString();
	}
	
	public String deleteSql(String tablename,String dateCoulmns,String otherCondition,int day) {
		
		StringBuffer bakSql = new StringBuffer();
		bakSql.append("delete from "+tablename);
		bakSql.append(" where ");
		bakSql.append("date_format("+dateCoulmns+",'%Y%m%d') <");
		bakSql.append("'"+LocalDateTime.now().plusDays(-20).format(DateTimeFormatter.ofPattern("yyyyMMdd"))+"'");
		if(StringUtils.hasLength(otherCondition)) {
			bakSql.append("and "+otherCondition);
		}
		return bakSql.toString();
	}
	
}
